<template>
  <view class="data-index fullpage-min bg-f5 body">
    <nav-bar title="智慧水位/桥粱净空高度" hideBack>
      <view class="" slot="left" @click="openUserInfo">
        <u-icon style="margin-right: 5rpx" name="account-fill"></u-icon>
        我的
      </view>
    </nav-bar>
    <!-- 切换数据 -->
    <!-- <view class="selectBox">
      <uni-section>
        <uni-data-select
          v-model="value"
          :localdata="range"
          @change="changeSelect"
        ></uni-data-select>
      </uni-section>
    </view> -->
    <!-- 水位数据看板 -->
    <view class="main" v-if="current == 2">
      <text-block :content="orderCountData"></text-block>

      <u-gap height="40"></u-gap>
      <!-- <view class="row_block">
        <view class="the_title" style="justify-content: space-between">
          <view class="left_title">
            <view class="title_icon"></view>
            <text class="margin_stand-samll font-big wide">{{
              locations.name + "水位平均统计|" + newDate
            }}</text>
          </view>
          <view class="right_btn">
            <view
              v-for="(item, index) in historyBtn"
              :key="index"
              :class="item.state ? 'active_btn' : ''"
              @click="changeHistoryBtn(item.type)"
              >{{ item.name }}</view
            >
          </view>
        </view>
        <view class="charts-box" style="height: 200px">
          <qiun-data-charts
            type="line"
            canvasId="finance_a"
            :disableScroll="true"
            :ontouch="true"
            :enableScroll="true"
            :canvas2d="isCanvas2d"
            :resshow="delayload"
            :opts="optsData"
            :chartData="orderData"
          />
        </view>
      </view> -->
    </view>
    <!-- 表格 -->
    <view class="tableData">
      <uni-table border stripe emptyText="暂无更多数据">
        <!-- 表头行 -->
        <uni-tr>
          <uni-th align="center">日期</uni-th>
          <uni-th align="center">位置</uni-th>
          <uni-th align="center">水位</uni-th>
          <uni-th align="center">查看详细</uni-th>
        </uni-tr>
        <!-- 表格数据行 -->
        <!-- <uni-tr>
          <uni-td align="center">2020-10-20</uni-td>
          <uni-td align="center">财富码头</uni-td>
          <uni-td align="center">2.21米</uni-td>
          <uni-td align="center">
            <text @click="watchWaterlevel" class="textBottom"
              >查看水位</text
            ></uni-td
          >
        </uni-tr> -->
        <uni-tr v-for="item in tableData" :key="item.id">
          <uni-td align="center">{{ item.time }}</uni-td>
          <uni-td align="center">{{ item.name }}</uni-td>
          <uni-td align="center">{{ item.data.waterv1.toFixed(2) }}米</uni-td>
          <uni-td align="center">
            <text @click="watchWaterlevel({ item })" class="textBottom"
              >查看水位</text
            ></uni-td
          >
        </uni-tr>
      </uni-table>
    </view>
    <!-- 底部 -->
    <view class="bottomBox">
    @国家85高程/广州海事科技
    </view>
    <u-popup v-model="isShow" width="400">
      <view class="user_info">
        <view class="headimage text-center">
          <image
            src="../../static/default-avatar.jpg"
            style="width: 140rpx; height: 140rpx; border-radius: 50%"
            mode=""
          ></image>
          <view class="size-32 m-top-10 color-6">{{ username }}</view>
        </view>
      </view>
      <u-gap height="50"></u-gap>

      <!-- <view
        class="lump flex-row p-left-20 p-right-20 p-botoom-20 color-6 border-bottom m-botoom-20"
        @click="showShopSelect = true"
      >
        <view>所在门店：</view>
        <view class="flex-2">湖美店</view>
        <u-icon color="#999" name="arrow-right"></u-icon>
      </view>
      <view
        class="lump flex-row p-left-20 p-right-20 p-botoom-20 color-6 border-bottom m-botoom-20"
        @click="clickBtn(1)"
      >
        <view class="flex-2">门店资料：</view>
        <u-icon color="#999" name="arrow-right"></u-icon>
      </view>
      <view
        class="lump flex-row p-left-20 p-right-20 p-botoom-20 color-6 border-bottom m-botoom-20"
        @click="clickBtn(2)"
      >
        <view class="flex-2">店铺公告：</view>
        <u-icon color="#999" name="arrow-right"></u-icon>
      </view>
      <view
        class="lump flex-row p-left-20 p-right-20 p-botoom-20 color-6 border-bottom m-botoom-20"
        @click="clickBtn(3)"
      >
        <view class="flex-2">通讯联系：</view>
        <u-icon color="#999" name="arrow-right"></u-icon>
      </view>
      <view
        class="lump flex-row p-left-20 p-right-20 p-botoom-20 color-6 border-bottom m-botoom-20"
        @click="clickBtn(4)"
      >
        <view class="flex-2">查看监控：</view>
        <u-icon color="#999" name="arrow-right"></u-icon>
      </view>
      <view
        class="lump flex-row p-left-20 p-right-20 p-botoom-20 color-6 border-bottom m-botoom-20"
        @click="clickBtn(5)"
      >
        <view class="flex-2">总部通知：</view>
        <view class="flex-row ai-center">
          <view style="color: #f82727"> 3 </view>
          <u-icon color="#999" name="arrow-right"></u-icon>
        </view>
      </view>
      <view
        class="lump flex-row p-left-20 p-right-20 p-botoom-20 color-6 border-bottom m-botoom-20"
        @click="clickBtn(6)"
      >
        <view class="flex-2">门店须知：</view>
        <u-icon color="#999" name="arrow-right"></u-icon>
      </view> -->
      <view
        class="pos-absolute"
        style="bottom: 30rpx; left: 20rpx; right: 20rpx"
      >
        <g-button size="large" round type="primary" @click="loginOut"
          >退出登陆</g-button
        >
      </view>
    </u-popup>
  </view>
</template>

<script>
import {
  waterLevelAjax,
  getWaterLlevel,
  realTimeWaterLevel,
  realTimeBridgeHeight,
} from "@/pages/data//api/index";
import store from "../../store/modules/user";
export default {
  created() {},
  data() {
    return {
      tableData: [], //表格数据
      optsData: {}, //图表配置
      current: 2,
      isCanvas2d: this.$f.ISCANVAS2D,
      newDate: "", //获取今天日期
      historyBtn: [
        {
          name: "今日",
          state: 1,
          type: "expend",
        },
        // {
        //   name: "上周",
        //   state: 0,
        //   type: "income",
        // },
      ],
      historyData: this.simulated.historyData,
      amountData: this.simulated.amountData,
      goods_sales: this.simulated.goods_sales,
      // orderData: this.simulated.orderData,
      orderData: {},
      moneyData: this.simulated.moneyData,
      userData: this.simulated.userData,
      // orderCountData: this.simulated.orderCountData,
      orderCountData: [],
      goodsData: this.simulated.goodsData,
      delayload: false,
      isShow: false,
      showShopSelect: false,
      //实时水位数据
      ajaxData: [],
      //清除定时器
      outTime: "",
      //水位设备列表默认值
      value: "1",
      range: [
        // { value: 0, text: "篮球" },
        // { value: 1, text: "足球" },
        // { value: 2, text: "游泳" },
      ],
      locations: {
        name: "财富码头", //统计表名称
        num: 2576484,
      },
    };
  },
  computed: {
    username() {
      return this.$store.state.user.user.username;
    },
  },
  async mounted() {
    // this.optsData = {
    //   // dataLabel:false,
    //   enableScroll: true, //开启滚轮
    //   xAxis: { disableGrid: true, itemCount: 6, scrollShow: true },
    //   yAxis: { disableGrid: true },
    //   // yAxis: { disableGrid: true, data: [{ disabled: true }]  },
    //   extra: {
    //     line: {
    //       type: "curve",
    //       width: 2,
    //       activeType: "hollow",
    //       linearType: "custom",
    //     },
    //   },
    // };

    // //获取今天日期
    // const now = new Date();
    // const year = now.getFullYear(); // 年份，如 2025
    // const month = now.getMonth() + 1; // 月份需加1（0-11 → 1-12）[4,5](@ref)
    // const day = now.getDate();
    // //接受今天日期
    // this.newDate = year + "-" + month + "-" + day;

    this.getwaterLevelList();
    // 确认返回true值 确保数据返回再启动定时器
    let res = await this.waterLevelInit();
    // if (res === true) {
    //   this.outTime = setInterval(() => {
    //     this.waterLevelInit();
    //   }, 15000);
    // }
  },
  methods: {
    //跳转查看水位
    watchWaterlevel(data) {
      //在起始页面跳转到test.vue页面并传递参数
      uni.navigateTo({
        url: `/pageWaterLevel/waterLevel/index`,
        success: (res) => {
          // 向子页面发送数据
          res.eventChannel.emit("parentEvent", data.item);
        },
      });
    },
    //切换数据
    // async ajaxInit(data) {
    //   //清除定时数据
    //   clearInterval(this.outTime);
    //   //切换选择值
    //   this.locations.num = data;
    //   // 确认返回true值 确保数据返回再启动定时器
    //   let res = await this.waterLevelInit(String(data));

    //   if (res === true) {
    //     this.outTime = setInterval(() => {
    //       this.waterLevelInit(String(data));
    //     }, 15000);
    //   }
    // },
    //水位设备列表选择值
    // changeSelect(e) {
    //   console.log("e:", e);
    //   //清除定时数据
    //   clearInterval(this.outTime);
    //   this.outTime = setInterval(() => {
    //     this.waterLevelInit(e);
    //   }, 5000);
    // },
    //异步水位数据
    async waterLevelInit(num) {
      // let res = await waterLevelAjax({ deviceId: num || "1" });
      // let res = await waterLevelAjax({ deviceId: num || "2576485" });
      let result = await realTimeWaterLevel();
      let resultBridgeHeight = await realTimeBridgeHeight();
      // this.ajaxData = res[1].data.data.data;

      // 请求获取当前1小时内数据  后台已处理每分钟一条数据
      let getHourData = result[1].data.data.data;
      //净高空数据
      let bridgeHeightData = resultBridgeHeight[1].data.data;
      //提取循环最后一条5分钟数据
      let getFiveData =  this.fiveMinutes(getHourData)
      let getbridgeHeightData =  this.fiveMinutes(bridgeHeightData)
      //提供给表格数据
      this.tableData = getFiveData;
      //渲染处理净高空数据
      this.deviceStatus(getbridgeHeightData);
      //添加和处理时间
      this.tableData.forEach((item) => {
        let date = new Date(item.data.colltime * 1000); //校正时间s
        let year = date.getFullYear(); // 年份，如2025[1,4](@ref)
        let month = date.getMonth() + 1; // 月份需加1（0-11对应1-12月）[1,6](@ref)
        let day = date.getDate(); // 日期（1-31）[1,4](@ref)

        let hoursDate = date.getHours();
        let minutes = date.getMinutes();
        item.data.waterv1 = item.data.waterv1 / 1000
        // 解决时间单0问题
        if (minutes <= 9) {
          minutes = "0" + minutes;
        }
        if (hoursDate <= 9) {
          hoursDate = "0" + hoursDate;
        }
        item.time =
          year + "-" + month + "-" + day + "/" + hoursDate + ":" + minutes;
      });

      // if (result[1].statusCode === 200) {
      //   let selectNameList = [];

      //   this.range.forEach((item) => {
      //     selectNameList.push({ id: item.value, name: item.text });
      //   });

      //   let nameData = selectNameList.find(
      //     (item) => item.id === this.locations.num
      //   );

      //   this.locations.name = nameData.name;
      // }

      //处理数据分类时间段
      // let groupedData = this.groupByHour(this.ajaxData);
      //处理时间水位数据
      // let huorList = this.averageData(groupedData);
      //处理时间和数据
      // let huorList = this.gettimeAndData(this.ajaxData);
      // this.setchartData(huorList);

      // if (res[1].statusCode && result[1].statusCode === 200) {
      //   return true;
      // } else {
      //   return false;
      // }
    },
    //提取最新5分钟工具函数
    fiveMinutes(data) {
      let getFiveData = []; // 提取最新5分钟数据变量
      //提取循环最后一条5分钟数据
      data.forEach((Element) => {
        getFiveData.push({
          name: Element.DeviceName,
          data: Element.data[Element.data.length - 1],
        });
      });

      return getFiveData
    },
    //异步获取水位设备列表
    async getwaterLevelList() {
      let res = await getWaterLlevel();
      let selectList = res[1].data.data.data;
      this.range = selectList.map((item) => {
        return { value: item.DeviceId, text: item.DeviceName };
      });
    },
    deviceStatus(ajaxData) {
      this.orderCountData = [];
      //处理水位数据
      ajaxData.forEach((item) => {
        item.data.bridge_high = item.data.bridge_high / 1000;
        this.orderCountData.push({
          kind: 4,
          id: item.data.id,
          background: ["#0081ff", "#1cbbb4"],
          content: [
            {
              text: item.data.name + '/' + '推算净空高度',
              value: "",
              colortext: "#fff",
              colorvalue: "",
              size: "24rpx",
            },
            {
              text: "",
              value: item.data.bridge_high.toFixed(1) + "米",
              colortext: "",
              colorvalue: "#fff",
              size: "44rpx",
            },
          ],
        });
      });
    },
    setchartData(ajaxData) {
      // console.log(343,ajaxData);
      // let arr = [
      //   2.21, 2.22, 2.21, 2.3, 2.23, 2.21, 2.22, 2.21,
      // ];

      // const numArr = arr.map(Number); // 转换为数值数组：[2.21, 2.22, 2.21, 2.30, 2.23]

      this.orderData = {
        // categories: ["24号", "25号", "26号", "27号", "28号", "29号", "30号","1号", "22号", "23号", "4号", "5号", "6号", "7号",],
        categories: ajaxData.time,
        series: [
          {
            name: "水位/米",
            data: ajaxData.waterv1Data,
            // data: arr,
            // format: 'yAxisDemo1', // 关联自定义格式化函数
            type: "line",
            style: "curve",
            color: "#55ff00",
            unit: "",
          },
        ],
        yAxis: [
          {
            calibration: true,
            position: "left",
            title: "单位/元",
            titleFontSize: 12,
            unit: "",
            tofix: 0,
            min: 0,
            disableGrid: true,
          },
        ],
      };
    },
    //循环数据计算平均值
    // averageData(data) {
    //   let hourList = [];
    //   let count = -1;
    //   //获取对象长度赋值时间
    //   let globalTime = Object.keys(data);
    //   for (let [key, value] of Object.entries(data)) {
    //     count++;
    //     let res = this.DailyMean(value, count);
    //     hourList.push(res);
    //   }
    //   //提取水位最新7小时数据
    //   // let NewData = huorList.slice(-7)
    //   if (hourList.length > 7) {
    //     let NewData = hourList.slice(-7);
    //     let time = NewData.map((item) => item.hour);
    //     let data = NewData.map((item) => item.sum);
    //     return { time, data };
    //   } else {
    //     let time = hourList.map((item) => item.hour);
    //     let data = NewData.map((item) => item.sum);
    //     // let data = hourList.map((item) =>{ return{ name:"刺客",data:item.sum}});
    //     return { time, data };
    //   }
    // },
    ////处理时间和数据
    gettimeAndData(data) {
      //处理时间和保留2位小鼠
      data.forEach((item) => {
        let date = new Date(item.colltime * 1000); //校正时间s
        let hoursDate = date.getHours();
        let minutes = date.getMinutes();
        // 解决时间单0问题
        if (minutes <= 9) {
          minutes = "0" + minutes;
        }
        if (hoursDate <= 9) {
          hoursDate = "0" + hoursDate;
        }
        item.time = hoursDate + ":" + minutes;
        item.data = item.waterv1 / 1000;
      });
      //提取数据
      let time = data.map((item) => item.time);
      let waterv1Data = data.map((item) => item.data.toFixed(2));

      return { time, waterv1Data };
    },
    //执行平均值函数
    // DailyMean(data, count) {
    //   //时间戳获取小时
    //   let date = new Date(data[0].colltime * 1000); //校正时间s
    //   let hoursDate = date.getHours();
    //   let minutes = date.getMinutes();
    //   // 解决时间单0问题
    //   if (minutes <= 9) {
    //     minutes = "0" + minutes;
    //   }
    //   // 平均值计算结果
    //   // let num = 0;
    //   // //时间
    //   // data.forEach((element) => {
    //   //   num = num + element.waterv1;
    //   // });
    //   // let total = num / data.length;
    //   // let newTotal = Number(total) / 100;

    //   //使用第一个数据
    //   let waterv = data[0].waterv1 / 1000;
    //   return {
    //     hour: hoursDate + ":" + minutes,
    //     sum: String(waterv.toFixed(2)),
    //   };
    // },
    //分类时间段
    // groupByHour(dataArray) {
    //   let groups = {};
    //   dataArray.forEach((item) => {
    //     let hour = Math.floor(item.colltime / 3600);
    //     groups[hour] = groups[hour] || [];
    //     groups[hour].push(item);
    //   });
    //   return groups;
    // },
    change(e) {
      this.current = e;
    },
    openUserInfo() {
      this.isShow = true;
    },
    clickBtn(e) {
      let url = "/pagesUser/user/";
      switch (e) {
        case 1:
          url = url + "shop-data?id=" + 1;
          break;
        case 2:
          url = url + "shop-notices?id=" + 1;
          break;
        case 3:
          url = url + "staff-list?id=" + 1;
          break;
        case 4:
          url = url + "monitoring-list?id=" + 1;
          break;
        case 5:
          url = url + "headquarters-notices?id=" + 1;
          break;
        case 6:
          url = url + "shop-information?id=" + 1;
          break;
        default:
          break;
      }
      this.$f.jumpUrl(url);
    },
    loginOut() {
      //清除定时数据
      clearInterval(this.outTime);
      //跳转
      uni.redirectTo({
        url: "/pages/login/index",
      });
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .uni-section .uni-section-header {
  padding: 0;
  border-radius: 50rpx;
}
.bottomBox{
  color: #fff;
  margin-top: 300rpx;
  text-align: center;
}
.textBottom {
  color: #0fc3ff;
  border-bottom: 5rpx solid#0fc3ff;
}

::v-deep .tableData {
  margin-top: 10rpx;
  padding: 15rpx;
}

::v-deep.table--border {
  border-radius: 23rpx;
}

.body {
  height: 100%;
  background-color: $color-theme;
  margin: 0;
  padding-bottom: 20rpx;

  .main {
    width: 100%;
    padding: 0 20rpx;
    box-sizing: border-box;
    margin-top: 20rpx;

    .right_btn {
      float: right;
      display: flex;
      color: #ccc;
      font-size: 22rpx;

      view {
        line-height: 50rpx;
        height: 50rpx;
        margin: 0 20rpx;
      }

      .active_btn {
        padding: 0rpx 20rpx;
        border: 1px solid #ccc;
        border-radius: 40rpx;
      }
    }

    .row_block {
      width: 100%;
      box-sizing: border-box;
      background-color: #fff;
      border-radius: 12rpx;
      position: relative;
      padding: 20rpx;

      &::after {
        content: "";
        height: 0px;
        width: 92%;
        position: absolute;
        transform: translateX(-50%);
        left: 50%;
        bottom: 0;
        border-top: 1px dashed #ccc;
      }
    }

    .the_title {
      display: flex;
      align-items: center;

      .left_title {
        display: flex;
        align-items: center;
      }

      .title_icon {
        background-color: #7e7e7e;
        height: 40rpx;
        width: 10rpx;
        border-radius: 10rpx;
        margin-right: 20rpx;
        font-size: 16px;
        font-weight: 600;
      }
    }

    .view_item {
      padding: 30rpx 20rpx;

      .title {
        text-align: left;
        margin-bottom: 30rpx;
        font-size: 40rpx;
      }
    }

    .progress_circle {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-around;
      align-items: center;
      height: 450rpx;

      .progress_block {
        width: 45%;
        border-radius: 20rpx;
        height: 180rpx;
        position: relative;
        overflow: hidden;

        .name {
          color: #fff;
          font-size: 24rpx;
          position: absolute;
          top: 20rpx;
          left: 10rpx;
          max-width: 144rpx;
        }

        .value {
          color: #fff;
          font-size: 40rpx;
          position: absolute;
          top: 64rpx;
          left: 10rpx;
          max-width: 144rpx;
        }

        .circle {
          position: absolute;
          right: 8rpx;
          top: 16rpx;
        }

        .arcbar {
          position: absolute;
          right: -4rpx;
          top: 8rpx;
        }
      }

      .block_0 {
        background-color: #0fc3ff;
      }

      .block_1 {
        background-color: #ff6b8b;
      }

      .block_2 {
        background-color: #ffcb1d;
      }

      .block_3 {
        background-color: #3bdcaa;
      }
    }
  }
}

.user_info {
  padding: 80px 0rpx 40rpx 0;
}
</style>
